package com.tma.basicfragment.book;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.tma.basicfragment.R;

public class BookAdapter extends BaseAdapter {
    static final String TAG = "BookAdapter";
    private Activity mActivity;
    private List<Book> mBooks;
    private LayoutInflater mInflater;

    final int[] COVERS = { R.drawable.jhtp8, R.drawable.cpphtp7,
            R.drawable.cs2010fp, R.drawable.jhtp9, R.drawable.jhtp7,
            R.drawable.iw3htp5 };

    public BookAdapter(Activity a) {
        this(a, new ArrayList<Book>());
    }

    public BookAdapter(Activity a, List<Book> books) {
        mActivity = a;
        mBooks = books;
        mInflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public List<Book> getData() {
        return mBooks;
    }

    public int getCount() {
        return mBooks.size();
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    public Object getItem(int position) {
        return mBooks.get(position);
    }

    public long getItemId(int position) {
        Book book = mBooks.get(position);
        return Long.parseLong(book.getIsbn());
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.book_item, null);

            holder = new ViewHolder();
            holder.cover = (ImageView) convertView.findViewById(R.id.iv_thumbnail);
            holder.title = (TextView) convertView.findViewById(R.id.tv_title);
            holder.author = (TextView) convertView.findViewById(R.id.tv_author);
            holder.year = (TextView) convertView.findViewById(R.id.tv_year);
            holder.isbn = (TextView) convertView.findViewById(R.id.tv_isbn);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Book book = mBooks.get(position);

        holder.cover.setImageResource(COVERS[position]);
        holder.title.setText(book.getTitle());
        holder.author.setText(book.getAuthor());
        holder.year.setText(String.valueOf(book.getYear()));
        holder.isbn.setText(book.getIsbn());

        return convertView;
    }

    private static class ViewHolder {
        ImageView cover;
        TextView title;
        TextView author;
        TextView year;
        TextView isbn;
    }
}
